package com.cms.controller.front;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;

import com.cms.CommonAttribute;
import com.cms.entity.Brand;
import com.cms.entity.Product;
import com.cms.entity.ProductCategory;
import com.cms.entity.ProductFav;
import com.cms.routes.RouteMapping;

/**
 * Controller - 商品
 * 
 * 
 * 
 */
@RouteMapping(url = "/product")
public class ProductController extends BaseController{
	
	
	/**
	 * 详情页
	 */
	public void detail(){
		Long productId=getParaToLong(0);
		Product product = new Product().dao().findById(productId);
        if (product == null || BooleanUtils.isNotTrue(product.getIsMarketable())) {
            render(CommonAttribute.FRONT_RESOURCE_NOT_FOUND_VIEW);
            return;
        }
        if(getCurrentMember()!=null){
        	ProductFav productFav = new ProductFav().dao().findByMemberId(getCurrentMember().getId(), productId);
        	setAttr("isFav", productFav==null?false:true);
        }
        setAttr("product", product);
		render("/templates/"+getTheme()+"/"+getDevice()+"/product_detail.html");
	}
	
	/**
	 * 列表
	 */
	public void list(){
		String keyword = getPara("keyword");
		String tag = getPara("tag");
		Long brandId = getParaToLong("brandId");
		Long productCategoryId=getParaToLong("productCategoryId");
		Integer pageNumber = getParaToInt("pageNumber");
		String orderBy = getPara("orderBy");
		if(StringUtils.isNotBlank(orderBy)){
			if(orderBy.equals("createDateDesc")){
				orderBy="createDate desc";
			}
		}
		if(pageNumber==null){
			pageNumber=1;
		}
		int pageSize = 20 ; 
		setAttr("page",new Product().dao().findPage(pageNumber,pageSize,productCategoryId,brandId,true,keyword,tag,orderBy));
		if(productCategoryId!=null){
			setAttr("currentProductCategory",new ProductCategory().dao().findById(productCategoryId));
		}
		if(brandId!=null){
			setAttr("currentBrand",new Brand().dao().findById(brandId));
		}
		setAttr("productCategoryId", productCategoryId);
		setAttr("brandId", brandId);
		setAttr("orderBy", orderBy);
		setAttr("pageNumber",pageNumber);
		setAttr("keyword", keyword);
		setAttr("tag", tag);
		render("/templates/"+getTheme()+"/"+getDevice()+"/product_list.html");
	}
	
	/**
	 * 搜索
	 */
	public void search(){
		Integer pageNumber = getParaToInt("pageNumber");
		String orderBy = getPara("orderBy");
		String keyword = getPara("keyword");
		String tag = getPara("tag");
		if(pageNumber==null){
			pageNumber=1;
		}
		if(StringUtils.isNotBlank(orderBy)){
			if(orderBy.equals("createDateDesc")){
				orderBy="createDate desc";
			}
		}
		int pageSize = 20 ; 
		setAttr("page",new Product().dao().findPage(pageNumber,pageSize,null,null,true,keyword,tag,orderBy));
		setAttr("keyword", keyword);
		setAttr("tag", tag);
		render("/templates/"+getTheme()+"/"+getDevice()+"/product_search.html");
	}

}
